import React, { useState, useEffect } from 'react';
import styles from './Item.module.css';
import {
  Form,
  Button,
  Badge,
  Input,
  Select,
  DatePicker,
  Table,
  Pagination,
  Modal,
  message,
} from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import type { TableColumnsType, TableProps } from 'antd';
import axios from 'axios';
import ReactQuill from 'react-quill-new';
import 'react-quill-new/dist/quill.snow.css';
import moment from 'moment';
const { RangePicker } = DatePicker;

interface dataItem {
  id: number;
  projectid: number;
}

interface DataType {
  id: number;
}

interface AppendForm {
  companyid: number;
  title: string;
  address: string;
  end_time: string;
  start_time: any;
  dw_security: any;
  gr_security: any;
  operator_account: string;
  operator_password: any;
  accounting_account: string;
  accounting_password: any;
  manager_account: string;
  manager_password: any;
  editor: string;
}

export default function Item() {
  // 获取到分页的数据
  const [data, setdata] = useState<dataItem[]>([]);
  const [pageData, setPageData] = useState<dataItem[]>([]);
  // 富文本的内容
  const [value, setValue] = useState('');
  // 添加弹窗状态
  const [appendOpen, setappendOpen] = useState(false);
  // 添加弹窗表单声明
  const [append] = Form.useForm<AppendForm>();
  // 公司数据声明
  const [company, setcompany] = useState([{ id: 0, account: '', companylist: [] }]);
  // 编辑状态
  const [editState, seteditState] = useState(false);
  const [editData, seteditData] = useState<dataItem | null>(null);
  const [passState, setpassState] = useState(true);
  const [editID, seteditID] = useState<dataItem[]>([]);
  // 下架的弹窗状态
  const [deleteOpen, setdeleteOpen] = useState(false);
  // 下架的id
  const [deleteId, setdeleteId] = useState<any>(null);
  // 回收站的数据
  const [recycleData, setrecycleData] = useState<dataItem[]>([]);
  const [recyclePagedata, setrecyclePagedata] = useState<dataItem[]>([]);
  const [recycleState, setrecycleState] = useState(false);
  // 恢复弹窗
  const [recoverOpen, setrecoverOpen] = useState(false);
  const [recoverId, setrecoverId] = useState<any>(null);

  // 添加的表单验证
  const AddRules = {
    companyid: [{ required: true, message: '请选择公司标识' }],
    title: [{ required: true, message: '请输入项目名称' }],
    address: [{ required: true, message: '请输入项目地址' }],
    start_time: [{ required: true, message: '请选择时间' }],
    account: [{ required: true, message: '请输入账号' }],
    password: [
      { required: passState, message: '请输入密码' },
      { min: 6, message: '密码长度不能小于6位' },
      { max: 18, message: '密码长度不能大于18位' },
    ],
  };
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.post('/organization/project/index');
        setdata(response.data.data);
        setPageData(response.data.data);
      } catch (err) {
        console.error('请求失败:', err);
      }
    };
    // 公司接口请求
    const companyData = async () => {
      try {
        const response = await axios.post('/organization/index/index');
        setcompany(response.data.companylist);
      } catch (err) {
        console.error('请求失败:', err);
      }
    };
    // 回收站的数据请求
    const recycle = async () => {
      try {
        const response = await axios.post('/organization/project/index', { status: 1 });
        console.log(response.data);

        setrecycleData(response.data.data);
        setrecyclePagedata(response.data.data);
      } catch (err) {
        console.error('请求失败:', err);
      }
    };
    recycle();
    companyData();
    fetchData();
  }, []);

  // 声明当前页
  const [currentPage, setCurrentPage] = useState(1);
  // 声明当前页数量
  const [pageSize, setPageSize] = useState(10);
  // 计算分页后的数据
  const paginatedData = pageData.slice((currentPage - 1) * pageSize, currentPage * pageSize);
  // 处理分页变化
  const handlePageChange = (page: any, size: any) => {
    setCurrentPage(page);
    setPageSize(size);
  };

  const columns: TableColumnsType<dataItem> = [
    {
      title: '序号',
      width: 80,
      key: 'id',
      fixed: 'left',
      align: 'center',
      dataIndex: 'id',
    },
    {
      title: '项目名称',
      key: 'id',
      fixed: 'left',
      align: 'center',
      dataIndex: 'title',
    },
    {
      title: '公司标识',
      key: 'id',
      fixed: 'left',
      align: 'center',
      dataIndex: 'companyid',
    },
    {
      title: '公司名称',
      key: 'id',
      fixed: 'left',
      align: 'center',
      dataIndex: 'account',
    },
    {
      title: '项目地址',
      key: 'id',
      fixed: 'left',
      align: 'center',
      dataIndex: 'address',
    },
    {
      title: '开发时间',
      key: 'id',
      fixed: 'left',
      align: 'center',
      dataIndex: 'start_time',
    },
    {
      title: '结束时间',
      key: 'id',
      fixed: 'left',
      align: 'center',
      dataIndex: 'end_time',
    },
    {
      title: '操作',
      width: 200,
      key: 'id',
      fixed: 'left',
      align: 'center',
      render: (_, record) => (
        <div>
          <Button
            style={{ backgroundColor: '#409EFF', color: 'white', marginRight: '10px' }}
            color="red"
            variant="solid"
            onClick={() => editModal(record)}
          >
            编辑
          </Button>
          <Button
            style={{ backgroundColor: '#F56C6C', color: 'white' }}
            color="red"
            variant="solid"
            onClick={() => showdelete(record.id)}
          >
            下架
          </Button>
        </div>
      ),
    },
  ];

  const columnsrecycle: TableColumnsType<dataItem> = [
    {
      title: '序号',
      width: 80,
      key: 'id',
      fixed: 'left',
      align: 'center',
      dataIndex: 'id',
    },
    {
      title: '项目名称',
      key: 'id',
      fixed: 'left',
      align: 'center',
      dataIndex: 'title',
    },
    {
      title: '公司标识',
      key: 'id',
      fixed: 'left',
      align: 'center',
      dataIndex: 'companyid',
    },
    {
      title: '公司名称',
      key: 'id',
      fixed: 'left',
      align: 'center',
      dataIndex: 'account',
    },
    {
      title: '项目地址',
      key: 'id',
      fixed: 'left',
      align: 'center',
      dataIndex: 'address',
    },
    {
      title: '开发时间',
      key: 'id',
      fixed: 'left',
      align: 'center',
      dataIndex: 'start_time',
    },
    {
      title: '结束时间',
      key: 'id',
      fixed: 'left',
      align: 'center',
      dataIndex: 'end_time',
    },
    {
      title: '操作',
      width: 200,
      key: 'id',
      fixed: 'left',
      align: 'center',
      render: (_, record) => (
        <div>
          <Button
            style={{ backgroundColor: '#409EFF', color: 'white', marginRight: '10px' }}
            color="red"
            variant="solid"
            onClick={() => showrecover(record.id)}
          >
            恢复
          </Button>
        </div>
      ),
    },
  ];

  // 声明当前页
  const [srecyclecurrentPage, setsrecycleCurrentPage] = useState(1);
  // 声明当前页数量
  const [srecyclepageSize, setsrecyclePageSize] = useState(10);
  // 计算分页后的数据
  const srecyclepaginated = recyclePagedata.slice(
    (srecyclecurrentPage - 1) * srecyclepageSize,
    srecyclecurrentPage * srecyclepageSize,
  );
  // 处理分页变化
  const handlePagesrecycle = (page: any, size: any) => {
    setsrecycleCurrentPage(page);
    setsrecyclePageSize(size);
  };

  // 添加弹窗显示
  const showModal = () => {
    setappendOpen(true);
    seteditState(false);
    setpassState(true);
  };
  // 编辑回显函数
  const editModal = async (item: any) => {
    setappendOpen(true);
    seteditState(true);
    setpassState(false);
    console.log(item);
    seteditData(item);
    const response = await axios.post('/organization/project/edit', { id: item.id });
    seteditID(response.data.account);
    append.setFieldsValue({
      companyid: item.companyid,
      title: item.title,
      address: item.address,
      dw_security: item.dw_security,
      gr_security: item.gr_security,
      operator_account: response.data.account[0].account,
      accounting_account: response.data.account[1].account,
      manager_account: response.data.account[2].account,
      start_time: [
        item.start_time ? moment(item.start_time) : null,
        item.end_time ? moment(item.end_time) : null,
      ],
    });
  };
  // 添加弹窗隐藏
  const hideModal = () => {
    setappendOpen(false);
    append.resetFields();
  };
  // 添加确认事件
  const affirm = async () => {
    if (!editState) {
      try {
        const appendfromValue = append.getFieldsValue();
        await append.validateFields();
        appendfromValue.start_time = appendfromValue.start_time.map((date: any) =>
          date.format('YYYY-MM-DD'),
        );
        const param = {
          companyid: appendfromValue.companyid,
          title: appendfromValue.title,
          address: appendfromValue.address,
          end_time: appendfromValue.start_time[1],
          start_time: appendfromValue.start_time[0],
          dw_security: appendfromValue.dw_security,
          gr_security: appendfromValue.gr_security,
          account: [
            appendfromValue.operator_account,
            appendfromValue.accounting_account,
            appendfromValue.manager_account,
          ],
          password: [
            appendfromValue.operator_password,
            appendfromValue.accounting_password,
            appendfromValue.manager_password,
          ],
          project_type: [3, 2, 1],
        };
        const response = await axios.post('/organization/project/add', param);
        console.log(response.data);
        if (response.data.code == 1) {
          message.success('添加成功');
          setappendOpen(false);
          append.resetFields();
        }
      } catch (err) {
        console.error('请求失败:', err);
      }
    } else {
      if (!editData) {
        message.error('编辑数据异常');
        return;
      }
      try {
        const appendfromValue = append.getFieldsValue();
        await append.validateFields();
        appendfromValue.start_time = appendfromValue.start_time.map((date: any) =>
          date.format('YYYY-MM-DD'),
        );
        const ids = editID.map(({ id }) => id);
        const param = {
          projectid: editData.id,
          id: ids,
          companyid: appendfromValue.companyid,
          title: appendfromValue.title,
          address: appendfromValue.address,
          end_time: appendfromValue.start_time[1],
          start_time: appendfromValue.start_time[0],
          dw_security: appendfromValue.dw_security,
          gr_security: appendfromValue.gr_security,
          account: [
            appendfromValue.operator_account,
            appendfromValue.accounting_account,
            appendfromValue.manager_account,
          ],
          password: [
            appendfromValue.operator_password,
            appendfromValue.accounting_password,
            appendfromValue.manager_password,
          ],
          project_type: [3, 2, 1],
        };
        const response = await axios.post('/organization/project/add', param);
        console.log(response.data);
        if (response.data.code == 1) {
          message.success('编辑成功');
          setappendOpen(false);
          append.resetFields();
        }
      } catch (err) {
        console.error('请求失败:', err);
      }
    }
    return;
  };
  // 下架弹窗
  const showdelete = async (item: any) => {
    setdeleteOpen(true);
    setdeleteId(item);
  };
  // 下架弹窗隐藏
  const hidedelete = () => {
    setdeleteOpen(false);
  };
  // 下架确认
  const deleteData = async () => {
    try {
      const response = await axios.post('/organization/project/del', { id: deleteId });
      console.log(response.data);
      if (response.data.code === 1) {
        message.success('下架成功');
        setdeleteOpen(false);
      }
    } catch (err) {
      console.error('请求失败:', err);
      message.error('下架失败');
    }
  };
  // 回收站显示
  const recyclePop = () => {
    setrecycleState(true);
  };
  // 回收站隐藏
  const hiderecycle = () => {
    setrecycleState(false);
  };
  // 恢复显示
  const showrecover = (item: any) => {
    setrecoverOpen(true);
    setrecoverId(item);
  };
  // 恢复确认
  const recoverData = async () => {
    try {
      const response = await axios.post('/organization/project/back', { id: recoverId });
      console.log(response.data);
      if (response.data.code === 1) {
        message.success('恢复成功');
        setrecoverOpen(false);
      }
    } catch (err) {
      console.error('请求失败:', err);
      message.error('恢复失败');
    }
  };

  const hiderecover = () => {
    setrecoverOpen(false);
  };
  console.log(srecyclepaginated);

  return (
    <div>
      <p className={styles.title}>员工管理</p>
      <div className={styles.topBox}>
        <Input
          placeholder="请输入项目名称"
          className={styles.searchInput}
          prefix={<SearchOutlined />}
        />
        <div className={styles.topButBox}>
          <Badge color="#F56C6C" count={recycleData.length} overflowCount={999}>
            <Button
              style={{ backgroundColor: '#F56C6C', color: 'white' }}
              color="red"
              variant="solid"
              onClick={recyclePop}
            >
              回收站
            </Button>
          </Badge>
          <Button
            style={{ backgroundColor: '#0052CC', color: 'white', marginLeft: '15px' }}
            color="red"
            variant="solid"
            onClick={showModal}
          >
            新增
          </Button>
        </div>
      </div>
      <Table<dataItem>
        style={{ marginTop: '30px' }}
        bordered={true}
        className={styles.customTable}
        pagination={false}
        columns={columns}
        rowKey={(record) => record.id}
        dataSource={paginatedData}
        scroll={{ x: 'max-content' }}
      />
      <Pagination
        style={{ margin: '30px 0px' }}
        align="center"
        current={currentPage}
        pageSize={pageSize}
        total={pageData.length}
        showQuickJumper
        showSizeChanger
        showTotal={(total) => `共 ${total} 条数据`}
        onChange={handlePageChange}
        onShowSizeChange={(current, size) => handlePageChange(1, size)}
      />
      <Modal
        style={{ top: '0px' }}
        width={1000}
        title="添加项目"
        open={appendOpen}
        onOk={affirm}
        onCancel={hideModal}
        okText="确认"
        cancelText="取消"
      >
        <div className={styles.alertBox}>
          <Form form={append}>
            <Form.Item<AppendForm>
              labelCol={{ span: 3 }}
              className={styles.formItem}
              name="companyid"
              layout="horizontal"
              label="项目所属公司"
              rules={AddRules.companyid}
            >
              <Select
                options={company.map((item) => ({
                  value: item.id,
                  label: item.account,
                }))}
                placeholder="请选择项目所属公司"
                allowClear
              />
            </Form.Item>
            <Form.Item<AppendForm>
              labelCol={{ span: 3 }}
              className={styles.formItem}
              name="title"
              layout="horizontal"
              label="项目名称"
              rules={AddRules.title}
            >
              <Input placeholder="请输入项目名称" />
            </Form.Item>
            <Form.Item<AppendForm>
              labelCol={{ span: 3 }}
              className={styles.formItem}
              name="address"
              layout="horizontal"
              label="项目地址"
              rules={AddRules.address}
            >
              <Input placeholder="请输入项目地址" />
            </Form.Item>
            <Form.Item<AppendForm>
              labelCol={{ span: 3 }}
              className={styles.formItem}
              name="start_time"
              layout="horizontal"
              label="项目周期"
              rules={AddRules.start_time}
            >
              <RangePicker style={{ width: '100%' }} />
            </Form.Item>
            <div className={styles.formItemBox}>
              <Form.Item<AppendForm>
                labelCol={{ span: 8 }}
                className={styles.formItemBox_input}
                name="operator_account"
                layout="horizontal"
                label="操作员账号"
                rules={AddRules.account}
              >
                <Input placeholder="请输入操作员账号" />
              </Form.Item>
              <Form.Item<AppendForm>
                labelCol={{ span: 8 }}
                className={styles.formItemBox_input}
                name="operator_password"
                layout="horizontal"
                label="操作员密码"
                rules={AddRules.password}
              >
                <Input placeholder="请输入操作员密码" />
              </Form.Item>
            </div>
            <div className={styles.formItemBox}>
              <Form.Item<AppendForm>
                labelCol={{ span: 8 }}
                className={styles.formItemBox_input}
                name="accounting_account"
                layout="horizontal"
                label="项目会计账号"
                rules={AddRules.account}
              >
                <Input placeholder="请输入项目会计账号" />
              </Form.Item>
              <Form.Item<AppendForm>
                labelCol={{ span: 8 }}
                className={styles.formItemBox_input}
                name="accounting_password"
                layout="horizontal"
                label="项目会计密码"
                rules={AddRules.password}
              >
                <Input placeholder="请输入项目会计密码" />
              </Form.Item>
            </div>
            <div className={styles.formItemBox}>
              <Form.Item<AppendForm>
                labelCol={{ span: 8 }}
                className={styles.formItemBox_input}
                name="manager_account"
                layout="horizontal"
                label="项目经理账号"
                rules={AddRules.account}
              >
                <Input placeholder="请输入项目经理账号" />
              </Form.Item>
              <Form.Item<AppendForm>
                labelCol={{ span: 8 }}
                className={styles.formItemBox_input}
                name="manager_password"
                layout="horizontal"
                label="项目经理密码"
                rules={AddRules.password}
              >
                <Input placeholder="请输入项目经理密码" />
              </Form.Item>
            </div>
            <Form.Item<AppendForm>
              labelCol={{ span: 3 }}
              className={styles.formItem}
              name="gr_security"
              layout="horizontal"
              label="个人社保基数"
            >
              <Input placeholder="请输入个人社保基数" type="number" />
            </Form.Item>
            <Form.Item<AppendForm>
              labelCol={{ span: 3 }}
              className={styles.formItem}
              name="dw_security"
              layout="horizontal"
              label="个人社保基数"
            >
              <Input placeholder="请输入单位社保基数" type="number" />
            </Form.Item>
            <Form.Item<AppendForm>
              className={styles.formItem}
              name="editor"
              label="项目介绍"
              labelCol={{ span: 3 }}
            >
              <ReactQuill theme="snow" value={value} onChange={setValue} style={{ height: 200 }} />
            </Form.Item>
          </Form>
        </div>
      </Modal>
      <Modal
        title="下架"
        open={deleteOpen}
        onOk={deleteData}
        centered
        onCancel={hidedelete}
        okText="确认"
        cancelText="取消"
      >
        <div className={styles.deleteBox}>是否要下架当前项目?</div>
      </Modal>
      <Modal
        title="项目回收站"
        open={recycleState}
        onCancel={hiderecycle}
        centered
        okText="确认"
        cancelText="取消"
        width={1100}
      >
        <Table<dataItem>
          style={{ marginTop: '30px' }}
          bordered={true}
          className={styles.customTable}
          pagination={false}
          columns={columnsrecycle}
          rowKey={(record) => record.id}
          dataSource={srecyclepaginated}
          scroll={{ x: 'max-content' }}
        />
        <Pagination
          style={{ margin: '30px 0px' }}
          align="center"
          current={srecyclecurrentPage}
          pageSize={srecyclepageSize}
          total={recyclePagedata.length}
          showQuickJumper
          showSizeChanger
          showTotal={(total) => `共 ${total} 条数据`}
          onChange={handlePagesrecycle}
          onShowSizeChange={(current, size) => handlePagesrecycle(1, size)}
        />
      </Modal>
      <Modal
        title="恢复"
        open={recoverOpen}
        onOk={recoverData}
        centered
        onCancel={hiderecover}
        okText="确认"
        cancelText="取消"
      >
        <div className={styles.deleteBox}>是否要恢复当前项目?</div>
      </Modal>
    </div>
  );
}
